package com.huifaapp.mall.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.AllOrderAdapter;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.EveryBannerBean;
import com.huifaapp.mall.bean.GoodsSkuCountBean;
import com.huifaapp.mall.lib.CycleViewPager;
import com.huifaapp.mall.phone.bean.ADInfo;
import com.huifaapp.mall.phone.utils.ViewFactory;
import com.huifaapp.mall.uitils.UtilsImage;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * 每日必推
 * Created by Administrator on 2017/12/14.
 */

public class DailyWillPushActivity extends AppCompatActivity {
    private TabLayout tab_layout_daily;
    private ViewPager viewpager_daily;
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> list=new ArrayList<>();
    private int roomid;
    private ImageView iv_home_daily_will_push_back;
    private List<ImageView> views = new ArrayList<ImageView>();
    private List<ADInfo> infos = new ArrayList<ADInfo>();
    private CycleViewPager cycleViewPager;
    EveryBannerBean listBean;
    private ImageView iv_daily_will_push_banner_image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_daily_will_push_activity);
        Intent intent = getIntent();
        initView();
        list.add("今日精选");
        list.add("爆款分享");
        list.add("一键发朋友圈");

        roomid = intent.getIntExtra("roomid",0);
        AllOrderAdapter adapter=new AllOrderAdapter(getSupportFragmentManager(),fragments,list);
        viewpager_daily.setAdapter(adapter);
        tab_layout_daily.setupWithViewPager(viewpager_daily);
        tab_layout_daily.setTabsFromPagerAdapter(adapter);
        viewpager_daily.setCurrentItem(roomid);
        cycleViewPager = (CycleViewPager)getSupportFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_daily_will_push);

    }
    private void initView() {
        tab_layout_daily = (TabLayout) findViewById(R.id.tab_layout_daily);
        viewpager_daily = (ViewPager) findViewById(R.id.viewpager_daily);
        iv_home_daily_will_push_back= (ImageView) findViewById(R.id.iv_home_daily_will_push_back);
        iv_home_daily_will_push_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_daily_will_push_banner_image= (ImageView) findViewById(R.id.iv_daily_will_push_banner_image);
        LoadEverydayBanner();
        fragments.add(new TodaysSelectionFragment());
        fragments.add(new DetonationModelSharingFragment());
        fragments.add(new AFriendCircleFragment());
    }

    private void LoadEverydayBanner(){
        String url=ApiManager.EVERYDAY_BANNER;
        Log.e("ShopCartActivity","每日必推轮播url========="+ url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                 listBean = gson.fromJson(response,EveryBannerBean.class);
                if(listBean.getData().size()==1){
                    UtilsImage.uploadimageview(iv_daily_will_push_banner_image,listBean.getData().get(0).getImg(),"", DailyWillPushActivity.this);
                    if(listBean.getData().get(0).getLinkType().equals("h5")){
                        Intent intent=new Intent(DailyWillPushActivity.this,RankingRanNo1HtmlActivity.class);
                        intent.putExtra("url",listBean.getData().get(0).getValue());
                        intent.putExtra("title","专题");
                        startActivity(intent);
                    }
                        iv_daily_will_push_banner_image.setVisibility(View.VISIBLE);
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        ft.hide(cycleViewPager);
                        ft.commit();
                }else if(listBean.getData().size()==0){
                        iv_daily_will_push_banner_image.setVisibility(View.GONE);
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        ft.hide(cycleViewPager);
                        ft.commit();
                }else{
                        iv_daily_will_push_banner_image.setVisibility(View.GONE);
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        ft.show(cycleViewPager);
                        ft.commit();
                        configImageLoader();
                        initialize();
                    }
                }
        });
    }
    @SuppressLint("NewApi")
    private void initialize() {

        for(int i = 0; i < listBean.getData().size(); i ++){
            ADInfo info = new ADInfo();
            info.setUrl(listBean.getData().get(i).getImg());
            Log.e("轮播","lunboimage===="+listBean.getData().get(i).getImg());
            info.setContent("图片-->" + i );
            infos.add(info);
        }
        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(DailyWillPushActivity.this, infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(DailyWillPushActivity.this, infos.get(i).getUrl()));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(DailyWillPushActivity.this, infos.get(0).getUrl()));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(4000);

        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
                if(listBean.getData().get(position).getLinkType().equals("h5")){
                    Intent intent=new Intent(DailyWillPushActivity.this,RankingRanNo1HtmlActivity.class);
                    intent.putExtra("url",listBean.getData().get(position).getValue());
                    intent.putExtra("title","专题");
                    startActivity(intent);
                }
            }
        }

    };

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(DailyWillPushActivity.this.getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
}
